document.write('<link href="component/uploadify/uploadify.css" rel="stylesheet" type="text/css" />');
document.write('<script type="text/javascript" src="component/uploadify/swfobject.js"></script>');
document.write('<script type="text/javascript" src="component/uploadify/jquery.uploadify.v2.1.4.js"></script>');
document.write('<script src="dwrsystem/engine.js"></script>');
document.write('<script src="dwrsystem/interface/UploadAttachService.js"></script>');

/**
 * 使用案例：
 * 
 * body中加入
 *  <input id="fupload" name="fupload" type="file"/>
 * 	<div id="fileQueueDiv"></div>
 *	<span style="display: none" id="tempFolder"><%=(session.getAttribute("tempFolder") + "")%></span>
 * 
 * 
 * javascript中加入
 * 
 * $(function(){
		uploadify.addAttachments({objid:'13146968344308783985614',tempName:'13146968344308783985614',fileName:'Jellyfish - 副本.jpg',fileSize:595284,businessId:'13146968344308783985614'});
		uploadify.addAttachments({objid:'13146941058382943515145',tempName:'13146941058382943515145',fileName:'Lighthouse.jpg',fileSize:561276,businessId:'13146941058382943515145'});
		uploadify.attachUploadify('fupload','fileQueueDiv',{
			hostId:'79670617141277706786109',
			tempFolder:$('#tempFolder').html(),

			attachTableName:'T_TEST_ATTACHMENT',
			idColmunName:'ID',
			attachColmunName:'ATTACHMENT_CONTENT',
			hostIdColmunName:'WORK_ID',
			attachNameColmunName:'ATTACHMENT_NAME',
			attachSizeColmunName:'ATTACHMENT_SIZE'
		},{'queueSizeLimit' : '5'});
		uploadify.onAddBefore = function(){alert(2);};
		uploadify.onDelAfter = function(){alert(3);};
	});
 */
var uploadify = {
	/*
	 * fuploadId	//上传的input类型的主键
	 * fdivId		//附件显示位置   
	 * 
	 * operateAttachDB 可以操作数据库，不操作填写null或者不写。 对象json写法：
	 * {
	 *  hostId:'',							 //关联表字段内容。和hostIdColmunName配合使用
	 *  tempFolder:$('#tempFolder').html(), //临时文件保存路径，就这么写就可以了
	 * 
	 *	attachTableName:'',			//附件上传的表名字 例如'T_TEST_ATTACHMENT',
	 *	idColmunName:'',			//附件上传的表主键字段名称 例如'ID',
	 *	attachColmunName:'',		//附件上传的表附件内容字段名称一般为blob类型的 例如'ATTACHMENT_CONTENT',
	 *	hostIdColmunName:'',		//附件上传的表附件关联表的字段名称  例如'HOST_ID', (可以不写)
	 *	attachNameColmunName:'',	//附件上传的表附件名称字段名称 例如'ATTACHMENT_NAME',
	 *	attachSizeColmunName:'',	//附件上传的表附件大小字段名称  例如'ATTACHMENT_SIZE' (可以不写)
	 * }
	 * 
	 * 
	 * uploadifyConfig 配置上传参数
	 * 	{
	 *		'queueSizeLimit' : '',					//一次选择文件数量，默认是10
	 *		'auto':true,							//是否自动上传，默认是true
	 *		'fileExt':'*.jpg,*,png',				//上传文件类型。默认是*.*
	 *		'sizeLimit' : 10485760					//一次上传文件的大小，默认是10485760B(10M)
	 *	}
	 * 
	 * 
	 */
	attachUploadify : function (fuploadId,fdivId,operateAttachDB,uploadifyConfig){
		var defaultConfig = {
			'queueSizeLimit' : '10',
			'auto':true,
			'fileExt':'*.*',
			'fileDesc' :'*.*',//不需要参数传递，应该与fileExt的类型相同
			'sizeLimit' : 10485760	
		};
		if(uploadifyConfig){
			if(uploadifyConfig.queueSizeLimit!=null && uploadifyConfig.queueSizeLimit != ''){
				defaultConfig.queueSizeLimit = uploadifyConfig.queueSizeLimit;
			}
			if(uploadifyConfig.auto!=null && uploadifyConfig.auto != ''){
				defaultConfig.auto = uploadifyConfig.auto;
			}
			if(uploadifyConfig.fileExt!=null && uploadifyConfig.fileExt != ''){
				defaultConfig.fileExt = uploadifyConfig.fileExt;
				defaultConfig.fileDesc = uploadifyConfig.fileExt;
			}
			if(uploadifyConfig.sizeLimit!=null && uploadifyConfig.sizeLimit != ''){
				defaultConfig.sizeLimit = uploadifyConfig.sizeLimit;
				defaultConfig.fileDesc = uploadifyConfig.fileExt;
			}			
		}
		configUploadify(fuploadId,fdivId,operateAttachDB,defaultConfig);
	},
	/*
	 * attachment 对象json写法：
	 * 
	 * {
	 * 	objid:'',			//'页面的元素id',
	 * 	tempName:'',		//'服务硬盘上保存的名字',
	 * 	fileName:'',		//'显示的的名字',
	 * 	fileSize: 1111,		//'文件大小',
	 * 	businessId:'',		//'表中业务字段'
	 * }
	 */
	addAttachments : function (attachment){
		attachments.push(attachment);
	},
	//获取所有附件内容
	getAttachments:function (){
		return attachments;
	},
	getAttachmentsString:function(){
		var result = '';
		for(var i=0;i<attachments.length;i++){
			var a = attachments[i];
			if(result != '')result += (','+a.tempName+'&'+attachments[i].fileName);
			else result += (a.tempName+'&'+attachments[i].fileName);
		}
		return result;
	},
	onAddBefore:function(){

	},
	onAddAfter:function(){
		
	},
	onDelBefore:function(){
		
	},
	onDelAfter:function(){
		
	}
};

var attachments = new Array();

function configUploadify(fuploadId,fdivId,operateAttachDB,uploadifyConfig){
	initUploadifyItem(fuploadId,fdivId);
	$('#' + fuploadId).uploadify({
		//page
		'uploader' : 'component/uploadify/uploadify.swf',//组件自带的flash
		'cancelImg' : 'component/uploadify/cancel.png',//取消上传文件的按钮图片
		'queueID' : fdivId,//放置上传文件及上传进度的Html元素Id
		'queueSizeLimit' : uploadifyConfig.queueSizeLimit,//一次最多选择多少个文件上传
		'buttonImg' : 'component/uploadify/selectbutton.png',
		//'buttonText' : 'upload',
		//control
		'auto' : uploadifyConfig.auto,//是否选取文件后自动上传,建议关闭
		'multi' : true,//多文件上传必须打开
		// 服务器脚本
		'method' : 'post',
		'script' : 'OperateFileAction!fileUpload.action', //Struts2下处理上传的action路径
		//'scriptData' : "{'userId': '12345'}",//自身业务需要向服务器端传递的数据
		// 传递给服务器参数
		'folder' : '/temp', //上传文件的目录，将作为'folder'参数传递给服务器
		'fileDataName' : 'document',//它决定了最重要的两个上传参数名称，本例中将为文件'photo'和文件名'photoFileName'
		'fileExt'        : uploadifyConfig.fileExt,//'*.gid;*.jpg;*.jpeg', //允许的文件类型，在客户端约束用户的文件选择，并将作为'fileext'参数传递给服务器供校验用
		// 其它
		'fileDesc'       : uploadifyConfig.fileDesc, //显示在本地选择文件对话框的文件类型下拉框中
    	'sizeLimit'      : uploadifyConfig.sizeLimit, // 单个文件的最大尺寸（字节B为单位）
    	'removeCompleted' : false,
    	'wmode'       : 'transparent',
    	'local':{'Completed':'完成'},
    	onComplete: function (event, queueID, fileObj, response, data) {
    		if(operateAttachDB){
    			operateAttachDB.attachName = fileObj.name;
    			operateAttachDB.attachSize = fileObj.size;
    			operateAttachDB.realAttachName = response;
    			uploadify.onAddBefore();
    			UploadAttachService.insertAttach(operateAttachDB,function(data){
    				uploadify.addAttachments({objid:queueID,tempName:response,fileName:fileObj.name,fileSize:fileObj.size,businessId:data});
    				uploadify.onAddAfter();
    			});
    		}else{
    			uploadify.addAttachments({objid:queueID,tempName:response,fileName:fileObj.name,fileSize:fileObj.size});
    		}
		},
		onError: function(event, queueID, fileObj) {
             alert("文件:" + fileObj.name + "上传失败"); 
        },
		onCancel : function(event,ID,fileObj,data) {
        	for(var i=0;i<attachments.length;i++){
        		if(ID == attachments[i].objid){
            		if(operateAttachDB){
            			uploadify.onDelBefore();
            			operateAttachDB.id=attachments[i].businessId;
            			UploadAttachService.deleteAttach(operateAttachDB,function(){
            				attachments = attachments.del(i);
            				uploadify.onDelAfter();
            			});
            		}else{
            			attachments = attachments.del(i);
            		}        			
        			break;
        		}
        	}
		}
	});
}

function initUploadifyItem(fuploadId,fdivId){
	var attachmentInit = 
		'<form action="OperateFileAction!downloadFile.action" name="downloadAttach" method="post" style="display:none;">'+
			'<input type="hidden" id="showFileName" name="showFileName" />'+
			'<input type="hidden" id="fileName" name="fileName" />'+
		'</form>';
	for(var i=0;i<attachments.length;i++){
		var attachment = attachments[i];
		var id = attachment.objid;
		var name = attachment.fileName;
		var size = attachment.fileSize;
		attachmentInit = attachmentInit+ ( '<div id="'+fuploadId + id +'" class="uploadifyQueueItem completed">'+
	  			'<div class="cancel">'+
					'<a href="javascript:jQuery(\'#'+fuploadId+'\').uploadifyCancel(\''+id+'\')">'+
						'<img border="0" src="component/uploadify/cancel.png">'+
					'</a>'+
				'</div>'+
	  			'<span class="fileName"><a href="javascript:jQuery(\'#'+fuploadId+'\').clickItemName(\''+id+'\')">'+name+'</a> (' + formateSize( size ) + ')</span>'+
				'<span class="percentage"> - 完成</span>'+
			'</div>' );
	}
	$('#' + fdivId).html(attachmentInit);
}

function formateSize(size){
	if(!size) return '';
	var byteSize = Math.round(size / 1024 * 100) * .01;
	var suffix = 'KB';
	if (byteSize > 1000) {
		byteSize = Math.round(byteSize *.001 * 100) * .01;
		suffix = 'MB';
	}
	var sizeParts = byteSize.toString().split('.');
	if (sizeParts.length > 1) {
		byteSize = sizeParts[0] + '.' + sizeParts[1].substr(0,2);
	} else {
		byteSize = sizeParts[0];
	}
	return byteSize + suffix;
}

function onClickItemName(ID){
	var am = null;
	for(var i=0;i<attachments.length;i++){
		if(ID == attachments[i].objid){
			am = attachments[i];
			break;
		}
	}
	if(am != null){
		downloadFile(am.tempName,am.fileName);
	}
}

function initBodyDownloadFileFrom(id){
	var attachmentInit = 
		$('#' + id).html()+
		'<form action="OperateFileAction!downloadFile.action" name="downloadAttach" method="post" style="display:none;">'+
			'<input type="hidden" id="showFileName" name="showFileName" />'+
			'<input type="hidden" id="fileName" name="fileName" />'+
		'</form>';
	$('#' + id).html(attachmentInit);
}

function downloadFile(fileName,showFileName){
	document.getElementById('fileName').value=fileName;
	document.getElementById('showFileName').value=showFileName;
	document.forms.downloadAttach.submit();
}

